package com.mymail.dao;


import java.sql.ResultSet;
import java.sql.SQLException;

import com.mymail.entity.User;

public class UserDAO extends DAOImp implements DAO {

	private int error = 1;

	public boolean getByName(String name, User user) {
		return findOne("select * from `user` where user_name=?",
				new String[] { name }, user);
	}

	public boolean findByEmail(String email, User user) {
		return findOne("select * from `user` where user_email=? ",
				new Object[] { email }, user);
	}

	public int getErrorCode() {
		return error;
	}

	public boolean getByID(Integer id, Object user) {
		String sql = "select * from `user` where user_id=?";
		return findOne(sql, new Object[] { id }, user);
	}

	public boolean delete(Object obj) {
		User user = (User) obj;
		String sql = "delete from `user` where user_id=?";
		return exe(sql, new Object[] { user.getId() });
	}

	public boolean toDatabase(Object obj) {
		User user = (User) obj;
		if (user.getId() == null) {
			return addNew(user);
		} else {
			return update(user);
		}
	}

	public boolean update(Object obj) {
		User user = (User) obj;
		String sql = "UPDATE `user` SET user_password=?,"
				+ "user_gender=?,user_birth=?, user_status=?, `user_phone`=?, `"
				+ "user_qq`=? WHERE (`user_id`=?)";
		return exe(sql, new Object[] { user.getPassword(),
				new String(new char[] { user.getGender() }), user.getBirth(),
				new String(new char[] { user.getGender() }), user.getPhone(),
				user.getQq(), user.getId() });
	}

	protected void setAtribute(ResultSet result, Object obj)
			throws SQLException {
		User user = (User) obj;
		user.setId(result.getInt("user_id"));
		user.setName(result.getString("user_name"));
		user.setEmail(result.getString("user_email"));
		user.setGender((char) result.getString("user_gender").getBytes()[0]);
		user.setPassword(result.getString("user_password"));
		user.setStatus((char) result.getString("user_status").getBytes()[0]);
		user.setPhone(result.getString("user_phone"));
		user.setQq(result.getString("user_qq"));
		user.setBirth(result.getDate("user_birth"));
	}

	protected User getEntity(ResultSet result) throws SQLException {
		User user = new User();
		setAtribute(result, user);
		return user;
	}

	/**
	 * 
	 * 
	 * 调用存储过程insert_user(OUT `result` int,IN `username` char(20),IN `pass`
	 * char(30),IN `email` char(30),IN `phone` char(15),IN `qq` char(12),IN
	 * `gender` char(1),IN bir char(20)) 向数据中插入新用户 第一个参数为返回值,与这个函数返回值意义相同
	 * 
	 */
	public boolean addNew(Object obj) {
		User user = (User) obj;
		String sql = "{call insert_user(?,?,?,?,?,?,?,?)}";
		int i = exeProcedure1(sql, new Object[] { user.getName(),
				user.getPassword(), user.getEmail(), user.getPhone(),
				user.getQq(), new String(new char[] { user.getGender() }),
				user.getBirth() });
		if (i > 0) {
			user.setId(i);
			return true;
		} else {
			error = i;
			return false;
		}
	}

}
